package com.king.zxing.app.util;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 */
public final class UriUtils {

    private UriUtils(){
        throw new AssertionError();
    }

    /**
     * 获取图片
     */
    public static String getImagePath(Context context,Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        //获取系統版本
        int currentapiVersion = Build.VERSION.SDK_INT;
        if(currentapiVersion> Build.VERSION_CODES.KITKAT){
            Log.d("uri=intent.getData :", "" + uri);
            if (DocumentsContract.isDocumentUri(context, uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                Log.d("getDocumentId(uri) :", "" + docId);
                Log.d("uri.getAuthority() :", "" + uri.getAuthority());
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String id = docId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                    imagePath = getImagePath(context,contentUri, null);
                }

            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                imagePath = getImagePath(context,uri, null);
            }
        }else{
            imagePath = getImagePath(context,uri, null);
        }

        return imagePath;

    }

    /**
     * 通过uri和selection来获取真实的图片路径,从相册获取图片时要用
     */
    private static String getImagePath(Context context,Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    /**
     * 复制文件夹及其中的文件
     *
     * @param oldPath String 原文件夹路径 如：/sdcard/Storagefactory/Json
     * @param newPath String 复制后的路径 如：外置挂载U盘目录
     * @return <code>true</code> if and only if the directory and files were copied;
     *         <code>false</code> otherwise
     */
    public static boolean copyAllFolder(String oldPath, String newPath, Context context) {

        if (newPath == null){
            Toast.makeText(context, "U盘不存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                if (!newFile.mkdirs()) {
                    Log.e("--Method--", "copyFolder: cannot create directory.");
                    return false;
                }
            }
            File oldFile = new File(oldPath);
            if (!oldFile.exists()) {
                Toast.makeText(context, "所要复制的路径不存在！", Toast.LENGTH_SHORT).show();
                return false;
            }
            String type = null;
            if (oldPath.substring(oldPath.length()-2).equals("QR")){
                type = ".jpg";
            }else if (oldPath.substring(oldPath.length()-4).equals("Json")){
                type = ".json";
            }
            String[] files = oldFile.list();
            File temp;
            boolean isexist = true;
            for (String file : files) {
                if (file.length()> 4 && file.substring(file.lastIndexOf('.')).equals(type)) {
                    isexist= false;
                    if (oldPath.endsWith(File.separator)) {
                        temp = new File(oldPath + file);
                    } else {
                        temp = new File(oldPath + File.separator + file);
                    }
                    if (temp.isDirectory()) {   //如果是子文件夹
                        copyAllFolder(oldPath + "/" + file, newPath + "/" + file,context);
                    } else if (!temp.exists()) {
                        Log.e("--Method--", "copyFolder:  oldFile not exist.");
                        return false;
                    } else if (!temp.isFile()) {
                        Log.e("--Method--", "copyFolder:  oldFile not file.");
                        return false;
                    } else if (!temp.canRead()) {
                        Log.e("--Method--", "copyFolder:  oldFile cannot read.");
                        return false;
                    } else {
                        FileInputStream fileInputStream = new FileInputStream(temp);
                        FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                        byte[] buffer = new byte[1024];
                        int byteRead;
                        while ((byteRead = fileInputStream.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0, byteRead);
                        }
                        fileInputStream.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                }
            }if (isexist){
                Toast.makeText(context,"未匹配到指定文件！",Toast.LENGTH_SHORT).show();
                return false;
            }else {
                Toast.makeText(context,"下载完成！",Toast.LENGTH_SHORT).show();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
        * 复制指定文件
     */
    public static boolean copyFolder(String oldPath, String newPath, String name, Context context) {
        String type = null;
        if (oldPath.substring(oldPath.length()-2).equals("QR")){
            type = ".jpg";
        }else if (oldPath.substring(oldPath.length()-4).equals("Json")){
            type = ".json";
        }
        if (newPath == null){
            Toast.makeText(context, "U盘不存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                if (!newFile.mkdirs()) {
                    Log.e("--Method--", "copyFolder: cannot create directory.");
                    return false;
                }
            }
            File oldFile = new File(oldPath);
            if (!oldFile.exists()) {
                    Toast.makeText(context, "所要复制的路径不存在！", Toast.LENGTH_SHORT).show();
                return false;
            }
            String[] files = oldFile.list();
            File temp;
            if (name.length()<=0 || name == null ){
                Toast.makeText(context,"指定数据名称不能为空!", Toast.LENGTH_SHORT).show();
                return false;
            }
            boolean isexist = true;
            for (int i=0;i<files.length;i++) {
                String file = files[i];
                for (int n=0;n<files.length;n++) {
                    if (type.equals(".jpg")){
                        name = name+n+type;
                    }else if(type.equals(".json")){
                        name = name+type;
                    }
                    if (file.equals(name)) {
                        isexist = false;
                        if (oldPath.endsWith(File.separator)) {
                            temp = new File(oldPath + file);
                        } else {
                            temp = new File(oldPath + File.separator + file);
                        }
                        if (temp.isDirectory()) {   //如果是子文件夹
                            copyFolder(oldPath + "/" + file, newPath + "/" + file,name,context);
                        } else if (!temp.exists()) {
                            Log.e("--Method--", "copyFolder:  oldFile not exist.");
                            return false;
                        } else if (!temp.isFile()) {
                            Log.e("--Method--", "copyFolder:  oldFile not file.");
                            return false;
                        } else if (!temp.canRead()) {
                            Log.e("--Method--", "copyFolder:  oldFile cannot read.");
                            return false;
                        } else {
                            FileInputStream fileInputStream = new FileInputStream(temp);
                            FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                            byte[] buffer = new byte[1024];
                            int byteRead;
                            while ((byteRead = fileInputStream.read(buffer)) != -1) {
                                fileOutputStream.write(buffer, 0, byteRead);
                            }
                            fileInputStream.close();
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                }
            }
            if (isexist){
                    Toast.makeText(context,"未匹配到指定文件！",Toast.LENGTH_SHORT).show();
                    return false;
            }else {
                Toast.makeText(context,"下载完成！",Toast.LENGTH_SHORT).show();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}